#define PI 3.1415
#define lightx 0.5
#define lighty 0.5
#define Threshold 0.1

precision highp float;

//varying vec3 n;
//varying vec2 uv;

uniform sampler2D texture;
uniform float width;

float getShadowDistanceH(vec2 uv);
float getShadowDistanceV(vec2 uv);
void main(void)
{
	vec2 uv = gl_TexCoord[0].xy;
	float distance = length(uv - 0.5);

	//distance stored in the shadow map
	float shadowMapDistance;
	//coords in [-1,1]
	float nY = uv.y - 0.5;
	float nX = uv.x - 0.5;

	//we use these to determine which quadrant we are in
	if (abs(nY)<abs(nX))
	{
		shadowMapDistance = getShadowDistanceH(uv);
	}
	else
	{
		//gl_FragColor = vec4(1., 0., 0., 1.);
		//return;
		shadowMapDistance = getShadowDistanceV(uv);
	}

	//if distance to this pixel is lower than distance from shadowMap,
	//then we are not in shadow
	float light = distance < shadowMapDistance ? 1. : 0.;
	vec4 result = vec4(light);
	result.a = 1.;

	gl_FragColor = result;
}


float getShadowDistanceH(vec2 uv)
{
	float column = uv.x > 0.5 ? 1.5 / width : 0.5 / width;
	float y = uv.y - 0.5;
	float x = uv.x - 0.5;
	float ysource = (x != 0 ? -0.5 * y / abs(x) : 0.);

	//horizontal info was stored in the Red component
	return texture2D(texture, vec2(column, ysource + 0.5)).r;
}

float getShadowDistanceV(vec2 uv)
{
	float column = uv.y > 0.5 ? 1.5 / width : 0.5 / width;
	float y = uv.y - 0.5;
	float x = uv.x - 0.5;
	float ysource = (y != 0 ? -0.5 * x / abs(y) : 0.);

	//horizontal info was stored in the Green component
	return texture2D(texture, vec2(column, ysource + 0.5)).g;
}